'use strict'

import { ipcMain, app, BrowserWindow, Notification, Menu, globalShortcut, clipboard, dialog, screen} from 'electron'
// const autoUpdater = require('electron-updater').autoUpdater
const log = require('electron-log')
// const Store = require('electron-store')
// const store = new Store()

// const recordMain = require('recordMain')

/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
// production
if (process.env.NODE_ENV !== 'development') {
  global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}

let mainWindow
const winURL = process.env.NODE_ENV === 'development'
  ? `http://localhost:9080`
  : `file://${__dirname}/index.html`

function createWindow () {
  /**
   * Initial window options
   */
  mainWindow = new BrowserWindow({
    height: 563,
    useContentSize: true,
    width: 1000,
    // frame: false,
    show: false,
    webPreferences: {
      nativeWindowOpen: true,
      plugins: true,
      nodeIntegration: true, // true 支持子页面node
      enableRemoteModule: true, // true 渲染器可以使用remote
      webSecurity: false,
      webviewTag: true,
      allowRunningInsecureContent: true,
      devTools: true
    }
  })
  log.info(__dirname)
  mainWindow.loadURL(winURL)

  mainWindow.on('closed', () => {
    mainWindow = null
  })
  mainWindow.once('ready-to-show', () => {
    mainWindow.show()
  })
  // 加载插件
  // BrowserWindow.addExtension('../../extensions/screen-recording')
}
// 系统通知
function showNotification (str) {
  const notification = {
    title: '通知',
    body: str
  }
  new Notification(notification).show()
}
// 系统通知

app.on('ready', () => {
  createWindow()
  showNotification('欢迎访问翼课堂')
  console.log('版本信息:' + process.versions)
  // 无需菜单
  Menu.setApplicationMenu(null)
  globalShortcut.register('ctrl+f12', () => {
    var w = BrowserWindow.getFocusedWindow()
    if (w) {
      w.webContents.toggleDevTools()
    }
  })
  if (process.env.NODE_ENV === 'production') {
    // 检查客户端更新
    // checkUpdate();
  }
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
})

// 主进行 渲染进程通讯
ipcMain.on('openRecord', e =>
  // recordMain.openRecord()
  openRecord()
)
// 开启录屏新窗口
var recorderWin
function openRecord () {
  const { width, height } = screen.getPrimaryDisplay().workAreaSize
  if (recorderWin) {
    return
  }
  recorderWin = new BrowserWindow({
    width: 650,
    height: 85,
    // parent: mainWindow, // win是主窗口
    modal: true,
    show: false,
    frame: false,
    resizable: false, // 窗口大小是否可以调整
    // alwaysOnTop: true, // 是否永远在别的窗口上层
    x: width / 2 - 300,
    y: 0,
    webPreferences: {
      nativeWindowOpen: true,
      plugins: true,
      nodeIntegration: true, // true 支持子页面node
      enableRemoteModule: true, // true 渲染器可以使用remote
      webSecurity: false,
      webviewTag: true,
      allowRunningInsecureContent: true,
      devTools: false
    }
  })
  log.info(__dirname)
  log.info(require('path'))
  log.info('11111:' + app.getPath('userData'))
  recorderWin.loadURL(winURL + '#/recordWin')
  mainWindow.minimize() // 最小化主窗口
  recorderWin.on('closed', () => {
    recorderWin = null
  })
  recorderWin.once('ready-to-show', () => {
    recorderWin.show()
  })
  // 调整窗口大小之前触发
  recorderWin.on('will-resize', (event, newBounds) => {
    log.info(newBounds.toLocaleString())
    event.preventDefault()
  })
}
/**
 * Auto Updater
 *
 * Uncomment the following code below and install `electron-updater` to
 * support auto updating. Code Signing with a valid certificate is required.
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-electron-builder.html#auto-updating
 */
/// //////////自动更新//////////////////////////////////
// const server = 'http://mis.9cair.com/mis2/update/'
// const url = server + process.platform + '/'
// autoUpdater.setFeedURL(url)
// function checkUpdate () {
//   autoUpdater.checkForUpdates()
// }
//
// autoUpdater.on('checking-for-update', () => {
//   log.info('【检查更新】：获取当前更新的 Feed 链接 ' + url)
// })
// autoUpdater.on('update-available', () => {
//   log.info('【检查更新】检查到有效版本，将开始自动下载')
// })
// autoUpdater.on('update-downloaded', (event, releaseNotes, releaseName) => {
//   log.info('【检查更新】最新版本已经下载完成')
//   const dialogOpts = {
//     type: 'info',
//     buttons: ['Later', 'Restart'],
//     title: 'Application Update',
//     message: process.platform === 'win32' ? releaseNotes : releaseName,
//     detail: 'A new version has been downloaded. Restart the application to apply the updates.'
//   }
//   dialog.showMessageBox(win, dialogOpts).then((index) => {
//     if (index.response == 1) {
//       autoUpdater.quitAndInstall()
//     }
//   })
// })
// autoUpdater.on('before-quit-for-update', (event, releaseNotes, releaseName) => {
//   log.info('【检查更新】应用重启更新成功，已调用quitAndInstall')
// })
// autoUpdater.on('error', message => {
//   log.error('【检查更新】更新出错：' + message)
// })
/// //////////自动更新//////////////////////////////////
